<template>
  <div>
    <div style="margin: 20px;">
      <el-button type="primary"
                 @click="showAddRuleDialog">添加条例</el-button>
      <el-button type="primary"
                 @click="showEditRuleDialog">修改条例</el-button>
      <el-button type="danger"
                 @click="showDeleteRuleDialog">删除条例</el-button>
    </div>
    <div style="margin: 10px;width:100%"
         :loading="loading">
      <div style="display:flex;flex-direction:column;justify-content:center;width:100%">
        <div class="title"
             style="display:flex;justify-content:center;margin-bottom: 10px;">
          物业级管理条例
        </div>
        <el-row>
          <el-col v-for="(item, index) in comRules"
                  :key="item"
                  :span="6"
                  :offset="index > 0 ? 1 : 0">
            <el-card :body-style="{ padding: '0px' }">
              <img :src="baseImgUrl + item.coverUrl"
                   class="image">
              <div style="padding: 14px;">
                <span>《{{ item.title }}》</span>
                <div>{{ item.brief }}</div>
                <div class="bottom clearfix">
                  <time class="time">修改时间 {{ item.modifyTime }}</time>
                  <el-button type="text"
                             class="button"
                             @click="showDetailDialog(item)">查看详细</el-button>
                  <!--                                    <el-button style="float: right" type="text" class="button" @click="showDetailDialog(item)">修 改</el-button>-->
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <el-divider />
      <div style="margin-top: 30px;display: flex;flex-direction: column">
        <div class="title"
             style="display:flex;justify-content:center;margin-bottom: 10px;">
          城市级物业管理条例
        </div>
        <el-row>
          <el-col v-for="(item, index) in cityRules"
                  :key="item"
                  :span="6"
                  :offset="index > 0 ? 1 : 0">
            <el-card :body-style="{ padding: '0px' }">
              <img :src="baseImgUrl + item.coverUrl"
                   class="image">
              <div style="padding: 14px;">
                <span>《{{ item.title }}》</span>
                <div>{{ item.brief }}</div>
                <div class="bottom clearfix">
                  <time class="time">修改时间 {{ item.modifyTime }}</time>
                  <el-button type="text"
                             class="button"
                             @click="showDetailDialog(item)">查看详细</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <el-divider />
      <div style="margin-top: 30px;display:flex;flex-direction: column">
        <div class="title"
             style="display:flex;justify-content:center;margin-bottom: 10px;">
          国家级物业管理条例
        </div>
        <el-row>
          <el-col v-for="(item, index) in countryRules"
                  :key="item"
                  :span="6"
                  :offset="index > 0 ? 1 : 0">
            <el-card :body-style="{ padding: '0px' }">
              <img :src="baseImgUrl + item.coverUrl"
                   class="image">
              <div style="padding: 14px;">
                <span>《{{ item.title }}》</span>
                <div>{{ item.brief }}</div>
                <div class="bottom clearfix">
                  <time class="time">修改时间 {{ item.modifyTime }}</time>
                  <el-button type="text"
                             class="button"
                             @click="showDetailDialog(item)">查看详细</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 条例详细dialog -->
    <el-dialog :title="ruleData.title"
               :visible.sync="rulesDetailDialog"
               width="60%"
               :before-close="handleClose">
      <div style="width:100%;height:500px;overflow-y: auto;overflow-x: hidden;word-wrap: break-word; word-break: break-all;"
           v-html="ruleData.content" />
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="rulesDetailDialog = false">返 回</el-button>
      </span>
    </el-dialog>

    <!-- 添加、修改条例dialog -->
    <el-dialog :title="dialogTitle"
               :visible.sync="addOrUpdateRuleDialog"
               width="60%"
               @close="cancelAddOrUpdateDialog">
      <el-form ref="form"
               :model="ruleInfo"
               label-width="150px"
               label-position="right">
        <el-form-item v-show="dialogTitle == '修改条例' ? true : false"
                      label="请选择要修改的条例">
          <el-cascader v-model="editRuleOption"
                       :options="ruleOptions"
                       :props="{ expandTrigger: 'hover' }"
                       @change="handleEditRuleChange" />
        </el-form-item>
        <el-form-item v-show="dialogTitle == '添加条例' ? true : false"
                      label="法律条例类型"
                      prop="type">
          <el-select v-model="ruleInfo.type"
                     placeholder="请选择法律条例类型"
                     clearable
                     size="small"
                     style="width: 240px">
            <el-option v-for="item in ruleOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="ruleInfo.title" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="ruleInfo.brief" />
        </el-form-item>
        <el-form-item label="封面">
          <el-upload class="avatar-uploader"
                     :limit="limitNum"
                     :action="uploadUrl"
                     accept="image/png,image/gif,image/jpg,image/jpeg"
                     :headers="headers"
                     :before-upload="handleBeforeUpload"
                     :on-remove="handleRemove"
                     :on-success="uploadSuccess"
                     :on-exceed="exceedFile"
                     :file-list="fileList">
            <img v-if="ruleInfo.coverUrl"
                 :src="baseImgUrl + ruleInfo.coverUrl"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip"
                 class="el-upload__tip">只能上传jpg/png/gif文件，且不超过2MB</div>
            <!--              <i slot="default" class="el-icon-plus" v-if="disabled"></i>-->
            <!--              <div slot="file" slot-scope="{file}">-->
            <!--                  <img-->
            <!--                          class="avatar"-->
            <!--                          :src="baseImgUrl + ruleInfo.coverUrl">-->
            <!--                  <span class="el-upload-list__item-actions">-->
            <!--                    <span-->
            <!--                            v-if="!disabled"-->
            <!--                            class="el-upload-list__item-preview"-->
            <!--                            @click="handlePictureCardPreview(file)">-->
            <!--                      <i class="el-icon-zoom-in"></i>-->
            <!--                    </span>-->
            <!--                    <span-->
            <!--                            v-if="!disabled"-->
            <!--                            class="el-upload-list__item-delete"-->
            <!--                            @click="handleRemove(file)">-->
            <!--                      <i class="el-icon-delete"></i>-->
            <!--                    </span>-->
            <!--                  </span>-->
            <!--              </div>-->
          </el-upload>
        </el-form-item>
        <!--        <el-form-item label="上传文件，支持word">-->
        <!--          <el-upload-->
        <!--            class="upload-demo"-->
        <!--            action="https://jsonplaceholder.typicode.com/posts/"-->
        <!--            accept=".text,.doc,.docx,.pdf"-->
        <!--            :on-preview="handlePreview"-->
        <!--            :on-remove="handleRemove"-->
        <!--            :before-remove="beforeRemove"-->
        <!--            multiple-->
        <!--            :limit="3"-->
        <!--            :on-exceed="handleExceed"-->
        <!--            :file-list="fileList"-->
        <!--          >-->
        <!--            <el-button size="small" type="primary">点击上传，自动解析</el-button>-->
        <!--            <div slot="tip" class="el-upload__tip">只能上传word/pdf文件，且不超过500kb</div>-->
        <!--          </el-upload>-->
        <!--        </el-form-item>-->
        <el-form-item label="内容">
          <div id="editor">
            <tinymce ref="content"
                     v-model="ruleInfo.content"
                     :height="300" />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelAddOrUpdateDialog">取 消</el-button>
        <el-button type="primary"
                   @click="doAddOrUpdateRule">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%"
           :src="dialogImageUrl"
           alt="">
    </el-dialog>

    <!-- 删除条例dialog -->
    <el-dialog title="删除条例"
               :visible.sync="deleteRuleDialog"
               width="60%">
      <el-alert title="注意请不要随便执行删除操作，该删除操作将会记录在系统中"
                type="warning" />
      <el-divider />
      <el-cascader v-model="deleteOption"
                   :options="ruleOptions"
                   :props="{ expandTrigger: 'hover' }" />
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelDeleteDialog">取 消</el-button>
        <el-button type="primary"
                   @click="deleteRule">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import { addNewRuleByData, getRulesList, updateRule, deleteRuleById, deleteRuleCoverByName } from '@/api/service/rules'
import { getToken } from '@/utils/auth'

export default {
  name: 'Rules',
  components: { Tinymce },
  data () {
    return {
      loading: false,
      comRules: [
        {
          coverUrl: '',
          title: '',
          brief: '',
          changeTime: '',
          content: ''
        }
      ],
      cityRules: [
        {
          coverUrl: '',
          title: '',
          brief: '',
          changeTime: '',
          content: ''
        }
      ],
      countryRules: [
        {
          coverUrl: '',
          title: '',
          brief: '',
          changeTime: '',
          content: ''
        }
      ],
      dialogTitle: '',
      rulesDetailDialog: false,
      ruleData: {
        title: '',
        content: ''
      },
      addOrUpdateRuleDialog: false,
      editRuleOption: '',
      ruleInfo: {
        type: '',
        title: '',
        brief: '',
        content: '',
        coverUrl: ''
      },
      ruleOptions: [
        {
          value: '物业级',
          label: '物业级',
          children: []
        },
        {
          value: '城市级',
          label: '城市级',
          children: []
        },
        {
          value: '国家级',
          label: '国家级',
          children: []
        }
      ],
      deleteRuleDialog: false,
      deleteOption: '',
      uploadUrl: process.env.VUE_APP_BASE_API + '/community/service/rules/uploadFile',
      headers: {
        Authorization: getToken()
      },
      limitNum: 1,
      limitSize: 2,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      baseImgUrl: 'http://82.157.106.150' + '/img/',
      fileList: []
    }
  },
  mounted () {
    this.initRuleList()
  },
  methods: {
    initRuleList () {
      this.loading = true
      getRulesList().then(resp => {
        if (resp) {
          console.log(resp)
          this.comRules = resp.data.community
          this.cityRules = resp.data.city
          this.countryRules = resp.data.country
          this.initRuleOptions()
          this.loading = false
        }
      })
    },
    initRuleOptions () {
      this.ruleOptions[0].children = []
      this.ruleOptions[1].children = []
      this.ruleOptions[2].children = []
      this.comRules.forEach(item => {
        this.ruleOptions[0].children.push({
          label: item.title,
          value: item.id
        })
      })
      this.cityRules.forEach(item => {
        this.ruleOptions[1].children.push({
          label: item.title,
          value: item.id
        })
      })
      this.countryRules.forEach(item => {
        this.ruleOptions[2].children.push({
          label: item.title,
          value: item.id
        })
      })
    },
    showDetailDialog (item) {
      this.ruleData.title = item.title
      this.ruleData.content = item.content
      this.rulesDetailDialog = true
    },
    showAddRuleDialog () {
      this.dialogTitle = '添加条例'
      this.addOrUpdateRuleDialog = true
    },
    cancelAddOrUpdateDialog () {
      console.log('清空内容')
      console.log(this.ruleInfo.coverUrl)
      if (this.dialogTitle === '添加条例' && (!(this.ruleInfo.coverUrl === '') && !(this.ruleInfo.coverUrl === undefined))) {
        deleteRuleCoverByName(this.ruleInfo.coverUrl).then(resp => {
          if (resp) {
            this.ruleInfo.coverUrl = ''
            console.log('删除成功')
          }
        })
      }
      this.fileList = []
      this.$refs.content.setContent('')
      this.ruleInfo = {}
      this.editRuleOption = ''
      this.addOrUpdateRuleDialog = false
    },
    doAddOrUpdateRule () {
      if (this.dialogTitle === '添加条例') {
        this.addNewRule()
      } else if (this.dialogTitle === '修改条例') {
        this.editRuleInfo()
      }
    },
    addNewRule () {
      addNewRuleByData(this.ruleInfo).then(resp => {
        if (resp) {
          this.initRuleList()
          this.cancelAddOrUpdateDialog()
          this.msgSuccess(resp.msg)
        }
      })
    },
    showEditRuleDialog () {
      this.dialogTitle = '修改条例'
      this.addOrUpdateRuleDialog = true
    },
    handleEditRuleChange (option) {
      console.log(option)
      if (option[0] === '物业级') {
        this.comRules.forEach(item => {
          if (item.id === option[1]) {
            this.ruleInfo = Object.assign({}, item)
            this.$refs.content.setContent(item.content)
          }
        })
      } else if (option[0] === '城市级') {
        this.cityRules.forEach(item => {
          if (item.id === option[1]) {
            this.ruleInfo = Object.assign({}, item)
            this.$refs.content.setContent(item.content)
          }
        })
      } else if (option[0] === '国家级') {
        this.countryRules.forEach(item => {
          if (item.id === option[1]) {
            this.ruleInfo = Object.assign({}, item)
            this.$refs.content.setContent(item.content)
          }
        })
      }
      // this.baseImgUrl = 'http://82.157.106.150/img/'
    },
    editRuleInfo () {
      console.log(this.ruleInfo)
      updateRule(this.ruleInfo).then(resp => {
        if (resp) {
          this.initRuleList()
          this.cancelAddOrUpdateDialog()
          this.msgSuccess(resp.msg)
        }
      })
    },
    showDeleteRuleDialog () {
      this.deleteRuleDialog = true
    },
    cancelDeleteDialog () {
      this.deleteOption = ''
      this.deleteRuleDialog = false
    },
    deleteRule () {
      console.log(this.deleteOption[1])
      deleteRuleById(this.deleteOption[1]).then(resp => {
        if (resp) {
          this.initRuleList()
          this.cancelDeleteDialog()
          this.msgSuccess(resp.msg)
        }
      })
    },
    // 文件超出个数限制时的钩子
    exceedFile (files, fileList) {
      this.$notify.warning({
        title: '警告',
        message: `只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`
      })
    },
    handleBeforeUpload (file) {
      const uploadLimit = this.limitSize
      // const uploadTypes = ['jpg', 'png', 'doc', 'docx', 'xlsx', 'zip', 'rar', 'pdf']
      const uploadTypes = ['jpg', 'png', 'gif']
      const filetype = file.name.replace(/.+\./, '')
      const isRightSize = (file.size || 0) / 1024 / 1024 < uploadLimit
      if (!isRightSize) {
        this.$message.error('文件大小超过 ' + uploadLimit + 'MB')
        return false
      }

      if (uploadTypes.indexOf(filetype.toLowerCase()) === -1) {
        this.$message.warning({
          message: '请上传后缀名为jpg、png、gif的附件'
        })
        return false
      }
      return true
    },
    uploadSuccess (response, file, fileList) {
      // this.baseImgUrl = 'http://82.157.106.150/img/'
      this.ruleInfo.coverUrl = response.data
    },
    handleRemove (file, fileList) {
      if (!(this.ruleInfo.coverUrl === '')) {
        deleteRuleCoverByName(this.ruleInfo.coverUrl).then(resp => {
          if (resp) {
            this.ruleInfo.coverUrl = ''
            console.log('删除成功')
          }
        })
      }
    }
  }
}
</script>

<style scoped>
.title {
  font-size: 24px;
  color: #666666;
}
.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
.avatar-uploader .el-upload {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.el-icon-plus {
  border: 1px dashed #8c939d;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
